//
//  NoteTools.m
//  MyNote
//
//  Created by Adiljan on 2016/11/22.
//  Copyright © 2016年 Adiljan. All rights reserved.
//

#import "NoteTools.h"
#import <UIKit/UIKit.h>
#import "FMDB.h"

#define SQL_NAME @"MyNote.sqlite"
@interface NoteTools()

@property (nonatomic, strong)FMDatabaseQueue *dbQueue;
@end

static FMDatabase *_fmdb;

@implementation NoteTools

// 创建表格
+ (void)initialize {
    // 执行打开数据库和创建表操作
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:SQL_NAME];
    _fmdb = [FMDatabase databaseWithPath:filePath];
    NSLog(@"Adiljan===>%@",filePath);
    [_fmdb open];
    
    #warning 必须先打开数据库才能创建表。。。否则提示数据库没有打开
    [_fmdb executeUpdate:@"CREATE TABLE IF NOT EXISTS t_modals(id INTEGER PRIMARY KEY, content TEXT NOT NULL, date INTEGER NOT NULL, time INTEGER NOT NULL);"];
}
+ (BOOL)insertModel:(NoteModel *)model {
    NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO t_modals(content, date, time) VALUES ('%@', '%@', '%@');", model.noteContent, model.createDate, model.createTime];
    return [_fmdb executeUpdate:insertSql];
}
// 查询
+ (NSArray *)queryData:(NSString *)querySql {
    
    if (querySql == nil) {
        querySql = @"SELECT * FROM t_modals;";
    }
    
    NSMutableArray *arrM = [NSMutableArray array];
    FMResultSet *set = [_fmdb executeQuery:querySql];
    
    while ([set next]) {
        
        NSString *content = [set stringForColumn:@"content"];
        NSString *time = [set stringForColumn:@"time"];
        NSString *date = [set stringForColumn:@"date"];
        
        NoteModel *modal = [NoteModel modelWith:content createDate:date createTime:time];
        [arrM addObject:modal];
    }
    return arrM;
}
// 删除
+ (BOOL)deleteData:(NSString *)deleteSql {
    
    if (deleteSql == nil) {
        deleteSql = @"DELETE FROM t_modals";
    }
    
    return [_fmdb executeUpdate:deleteSql];
    
}
// 修改数据
+ (BOOL)modifyData:(NSString *)modifySql {
    
    if (modifySql == nil) {
//        modifySql = @"UPDATE t_modals SET ID_No = '789789' WHERE name = 'lisi'";
    }
    return [_fmdb executeUpdate:modifySql];
}
+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}
/**
 *  16进制颜色值转RGB
 *
 *  @param hexString 16进制字符串色值
 *
 *  @return RGB色值
 */
+ (UIColor *)colorWithHexString:(NSString *)hexString
{
    NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if ([cString length] < 6)
        return [UIColor clearColor];;
    unsigned int alpha = 255;
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    NSRange range = NSMakeRange(0, 2);
    if ([cString length]==8) {
        [[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&alpha];
        cString = [cString substringFromIndex:2];
    }
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    
    
    unsigned int red, green, blue;
    [[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&red];
    
    range.location = 2;
    [[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&green];
    
    range.location = 4;
    [[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&blue];
    
    return [UIColor colorWithRed:((float)red / 255.0f)
                           green:((float)green / 255.0f)
                            blue:((float)blue / 255.0f)
                           alpha:((float)alpha / 255.0f)];
}
//// 单例模式
//+(NoteTools *)noteTools{
//    static NoteTools *noteTools =nil;
//    static dispatch_once_t once;
//    dispatch_once(&once, ^{
//        noteTools = [[NoteTools alloc]init];
//    });
//    return noteTools;
//}
//
///*Adiljan 创建表格*/
//-(void)createTable{
//    // 0.拼接数据库存放的沙盒路径
//    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
//    NSString *sqlFilePath = [path stringByAppendingPathComponent:@"note.sqlite"];
//    _dbQueue = [FMDatabaseQueue databaseQueueWithPath:sqlFilePath];
//    // 2.执行操作
//    // 会通过block传递队列中创建好的数据库
//    [_dbQueue inDatabase:^(FMDatabase *db) {
//        
//        BOOL success = [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, time TEXT);"];
//        
//        if (success) {
//            NSLog(@"创建表成功");
//        } else {
//            NSLog(@"创建表失败");
//        }
//        
//    }];
//}
//- (void)insertClick:(NSString *)title time:(NSString *)time {
//    
//    static NSInteger age = 10;
//    age++;
//    
//    [self.dbQueue inDatabase:^(FMDatabase *db) {
//        
//        BOOL success = [db executeUpdate:@"INSERT INTO t_student (title, time) VALUES (?, ?);", title, time];
//        
//        if (success) {
//            NSLog(@"插入成功");
//        } else {
//            NSLog(@"插入失败");
//        }
//    }];
//    
//}
//-(void)deleteClick:(NSInteger)ID{
//    // 删除数据
//    [self.dbQueue inDatabase:^(FMDatabase *db) {
//        
//        BOOL success = [db executeUpdate:@"DELETE FROM t_student WHERE ID > 2 VALUES(?);",ID];
//        if (success) {
//            NSLog(@"删除成功");
//        } else {
//            NSLog(@"删除失败");
//        }
//        
//    }];
//}
//-(void)updateClick{
//    // 修改数据
//    [self.dbQueue inDatabase:^(FMDatabase *db) {
//        
//        BOOL success = [db executeUpdate:@"UPDATE t_student SET name = 'liwx' WHERE age > 12 AND age < 15;"];
//        
//        // 判断是否SQL是否执行成功
//        // ...
//    }];
//}
//// 查询数据
//- (void)queryClick {
//    
//    [self.dbQueue inDatabase:^(FMDatabase *db) {
//        
//        FMResultSet *result = [db executeQuery:@"SELECT id, name, age FROM t_student WHERE age > 25;"];
//        
//        while ([result next]) {
//            int ID = [result intForColumnIndex:0];
//            NSString *name = [result stringForColumnIndex:1];
//            int age = [result intForColumn:@"age"];
//            
//            NSLog(@"ID: %zd, name: %@, age: %zd", ID, name, age);
//        }
//    }];
//    
//    
//}
@end
